//
//  BZLanguageManager.m
//  YiCuiMiaoZhang
//
//  Created by allen on 2018/12/5.
//  Copyright © 2018 益萃网络科技（中国）有限公司. All rights reserved.
//

#import "BZLanguageManager.h"
#import "NSBundle+Language.h"

static NSString * const LanguageSaveKey = @"currentLanguageKey";

NSString *const kLocaliedAssignCn = @"zh-Hans";
NSString *const kLocaliedAssignEn = @"en";

@interface BZLanguageManager()
@property (nonatomic, copy) NSArray *languageInfos;
@property (nonatomic, copy) NSArray *languageCodes;
@property (nonatomic, copy) NSArray *languageNames;

@property (nonatomic, strong, readwrite) NSBundle *languageBundle;

@end

@implementation BZLanguageManager

static BZLanguageManager *manager = nil;
+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[BZLanguageManager alloc] init];
    });
    return manager;
}

- (instancetype)init{
    if (self = [super init]) {
        NSString *path = [[NSBundle mzBasicBundle] pathForResource:@"LanguageInternational.plist" ofType:nil];
        self.languageInfos = [[NSArray alloc] initWithContentsOfFile:path];
        NSMutableArray *tempArr = [NSMutableArray new];
        NSMutableArray *tempStingArr = [NSMutableArray new];

        for (NSDictionary *dict in self.languageInfos) {
            [tempArr addObject:dict[@"code"]];
            [tempStingArr addObject:dict[@"language"]];
        }
        self.languageCodes = [tempArr copy];
        self.languageNames = [tempStingArr copy];
    }
    return self;
}

- (NSBundle *) languageBundle {
    _languageBundle = [NSBundle mainBundle];
    return _languageBundle;
}

#pragma mark - iOS 9.0以后 ，en->en_CN , zh-Hans -> zh-Hans-CN
- (void)setupCurrentLanguage
{

    NSString *currentCode = [[NSUserDefaults standardUserDefaults] objectForKey:LanguageSaveKey];
    if (!currentCode) {
        NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
        if (languages.count > 0) {
            currentCode = languages[0];
            if ([currentCode isEqualToString:@"en"]) {
                currentCode = @"en";
            }else{
                currentCode = @"zh-Hans";
            }
            [[NSUserDefaults standardUserDefaults] setObject:currentCode forKey:LanguageSaveKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else{
            currentCode = @"zh-Hans";
        }
    }

    [[NSUserDefaults standardUserDefaults] setObject:@[currentCode] forKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [NSBundle setLanguage:currentCode];
    
}

/**
 国际化版 设置默认语言 @"zh-Hans" @"en"
 */
- (void)setupInternationalDefaultLanguage:(BOOL)isEnglish {
    
    NSString *currentCode = [[NSUserDefaults standardUserDefaults] objectForKey:LanguageSaveKey];
    if (!currentCode) {
        if (isEnglish) {
            currentCode = @"en"; //默认英文
        }else{
            currentCode = @"zh-Hans"; //默认中文
        }
        [[NSUserDefaults standardUserDefaults] setObject:currentCode forKey:LanguageSaveKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [NSBundle setLanguage:currentCode];
}

- (NSString *)currentLanguageInfo:(LanguageInfoType)type;
{
    NSString *currentCode = [[NSUserDefaults standardUserDefaults] objectForKey:LanguageSaveKey];
    for (NSDictionary *dict in self.languageInfos) {
        if ([currentCode hasPrefix:dict[@"code"]]) {
            if (type == LanguageCode) {
                return dict[@"code"];
            }else if (type == LanguageServerType){
                return dict[@"type"];
            }else{
                return dict[@"language"];
            }
        }
    }
    return [[NSUserDefaults standardUserDefaults] objectForKey:LanguageSaveKey];
}

- (NSString *)getSelectLanguageType:(NSInteger)index{
    
    if (index < self.languageInfos.count) {
        return [[self.languageInfos objectAtIndex:index] objectForKey:@"type"];
    }else {
        return @"";
    }
}
- (NSString *)locatizedCurrentBundleWithName:(NSString *)local{
    NSString *currentCode = [self currentLanguageInfo:LanguageCode];
    NSBundle *currentBundle = [NSBundle bundleWithPath:[self.languageBundle pathForResource:currentCode ofType:@"lproj"]];
    NSString *path = [currentBundle pathForResource:local ofType:nil];
    if (path == nil || path.length == 0) {
        path = [self.languageBundle pathForResource:local ofType:nil];
    }
    return path;
}

- (NSString *)localizedStringForKey:(NSString *)key{
    NSString *currentCode = [self currentLanguageInfo:LanguageCode];
    NSBundle *currentBundle = [NSBundle bundleWithPath:[self.languageBundle pathForResource:currentCode ofType:@"lproj"]];
    NSString *string = [currentBundle localizedStringForKey:key value:@"" table:@"Localizable"];
    return string;
}

- (NSString *)localizedAssign:(NSString *) localized ForKey:(NSString *)key{
    NSBundle *currentBundle = [NSBundle bundleWithPath:[self.languageBundle pathForResource:localized ofType:@"lproj"]];
    NSString *string = [currentBundle localizedStringForKey:key value:@"" table:@"Localizable"];
    return string;
}


- (NSString *)localizedStringForKey:(NSString *)key jointString:(NSString *)str ShowKeyFirst:(BOOL)keyFirst{
    NSString *currentCode = [self currentLanguageInfo:LanguageCode];
    NSBundle *currentBundle = [NSBundle bundleWithPath:[self.languageBundle pathForResource:currentCode ofType:@"lproj"]];
    NSString *string = [currentBundle localizedStringForKey:key value:@"" table:@"Localizable"];
    return keyFirst?[NSString stringWithFormat:@"%@%@",string,str]:[NSString stringWithFormat:@"%@%@",str,string];
}

- (void)saveLanguageByIndex:(NSInteger)index sucess:(sucess)changeLanguageBlcok
{
    if (index >= 0 && index < _languageCodes.count) {
        NSString *code = _languageCodes[index];
        [[NSUserDefaults standardUserDefaults] setObject:code forKey:LanguageSaveKey];
        [[NSUserDefaults standardUserDefaults] synchronize];

        [NSBundle setLanguage:code];
    }
    if (changeLanguageBlcok) {
        changeLanguageBlcok();
    }
}

- (BOOL)currentLanguageIsEnglish{
    NSString *code = [self currentLanguageInfo:LanguageCode];
    if ([code hasPrefix:@"en"]) {
        return true;
    }
    return false;
}

- (NSArray *)AllLanguagesNames{
    return self.languageNames;
}

- (NSArray *)AllLanguagesCodes{
    return self.languageCodes;
}

- (NSString *) localizedImageNameWithName:(NSString *) imageName {
    NSString *returnImageName = imageName;
    if ([self currentLanguageIsEnglish]) {
        returnImageName = [NSString stringWithFormat:@"%@_en",imageName];
    }
    return returnImageName;
}

@end
